<!DOCTYPE html>
<html lang="zh-CN">





<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="兴趣使然的个人博客">
  <meta name="author" content="Ilirus">
  <meta name="keywords" content>
  <title>Vue Router的安装与使用 - Ilirus</title>

  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css">


  <link rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css">
  <link rel="stylesheet" href="/blog/lib/hint/hint.min.css">

  
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-light.min.css">
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link rel="stylesheet" href="/blog/css/main.css">

<!-- 自定义样式保持在最底部 -->


  <script src="/blog/js/utils.js"></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>Ilirus</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/blog/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-01-25 00:10">
      2019年1月25日 凌晨
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      24
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h1 id="Vue-Router-的基本用法"><a href="#Vue-Router-的基本用法" class="headerlink" title="Vue Router 的基本用法"></a>Vue Router 的基本用法</h1><h2 id="安装Vue路由"><a href="#安装Vue路由" class="headerlink" title="安装Vue路由"></a>安装Vue路由</h2><pre><code class="hljs batch">vue add @vue/router

:: 或者
npm install vue-router -S

yarn add vue-router</code></pre>
<h2 id="引入路由"><a href="#引入路由" class="headerlink" title="引入路由"></a>引入路由</h2><p>写在main.js文件中<br><pre><code class="hljs javascript"><span class="hljs-comment">// 引入Router</span>
<span class="hljs-keyword">import</span> Router <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-router'</span>;

<span class="hljs-comment">// 引入路由跳转的组件</span>
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Home'</span>;

<span class="hljs-comment">// 配置Router</span>
<span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> VueRouter(&#123;
  <span class="hljs-comment">// 路由模式 (hash | history | abstract(如果没有发现浏览器API, 会自动进入此模式))</span>
  <span class="hljs-comment">// 使用history模式可以去掉地址栏的'#'字符, 但需要后端配置支持</span>
  <span class="hljs-comment">// history 模式利用window.history API 来完成页面的跳转而无需重新加载页面</span>
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'history'</span>,
  <span class="hljs-attr">base</span>: process.env.BASE_URL,
  <span class="hljs-attr">routes</span>: [
    &#123;
      <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'home'</span>,
      <span class="hljs-attr">component</span>: Home
    &#125;, &#123;
      <span class="hljs-attr">path</span>: <span class="hljs-string">'/about'</span>,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'about'</span>,
      <span class="hljs-attr">component</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./views/About.vue'</span>)
    &#125;
  ]
&#125;)

<span class="hljs-comment">// 使用Router</span>
Vue.use(Router)

<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">router</span>: router,
  <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">h</span>) </span>&#123; <span class="hljs-keyword">return</span> h(App) &#125;
&#125;).$mount(<span class="hljs-string">'#app'</span>)</code></pre></p>
<p>写在template中<br><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- 使用路由名称跳转 --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-link</span> <span class="hljs-attr">:to</span>=<span class="hljs-string">"&#123;name:'home'&#125;"</span>&gt;</span>主页<span class="hljs-tag">&lt;/<span class="hljs-name">router-link</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-link</span> <span class="hljs-attr">:to</span>=<span class="hljs-string">"&#123;name:'about'&#125;"</span>&gt;</span>关于<span class="hljs-tag">&lt;/<span class="hljs-name">router-link</span>&gt;</span>

  <span class="hljs-comment">&lt;!-- 直接指定跳转路径 --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>主页<span class="hljs-tag">&lt;/<span class="hljs-name">router-link</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></code></pre></p>
<a id="more"></a>
<p>也可将Router配置抽离到单独的js文件中<br><pre><code class="hljs javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">new</span> VueRouter(&#123;
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'history'</span>,
  <span class="hljs-attr">base</span>: process.env.BASE_URL,
  <span class="hljs-attr">routes</span>: [
    &#123;
      <span class="hljs-comment">// 路径</span>
      <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
      <span class="hljs-comment">// 名称</span>
      <span class="hljs-attr">name</span>: <span class="hljs-string">'home'</span>,
      <span class="hljs-comment">// 挂载的组件</span>
      <span class="hljs-attr">component</span>: Home
    &#125;, &#123;
      <span class="hljs-attr">path</span>: <span class="hljs-string">'/about'</span>,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'about'</span>,
      <span class="hljs-comment">// 懒加载</span>
      <span class="hljs-attr">component</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./views/About.vue'</span>),
      <span class="hljs-comment">// 子路由</span>
      <span class="hljs-attr">children</span>: [&#123;
        <span class="hljs-attr">path</span>: <span class="hljs-string">'concat'</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">'concat'</span>,
        <span class="hljs-attr">component</span>: Concat
      &#125;,&#123;
        <span class="hljs-attr">path</span>: <span class="hljs-string">'guide'</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">'guide'</span>,
        <span class="hljs-attr">component</span>: Guide,
        <span class="hljs-comment">// 子路由下的子路由</span>
        <span class="hljs-attr">children</span>: [
          <span class="hljs-comment">// ...</span>
        ]
      &#125;],
      <span class="hljs-attr">redirect</span>: &#123;<span class="hljs-attr">name</span>: <span class="hljs-string">'concat'</span>&#125;
    &#125;, &#123;
      <span class="hljs-comment">// 匹配所有(上面没有匹配到的)</span>
      <span class="hljs-attr">path</span>: <span class="hljs-string">'*'</span>,
      <span class="hljs-comment">// 重定向</span>
      <span class="hljs-attr">redirect</span>: <span class="hljs-string">'/error/notfound'</span>
    &#125;
  ]
&#125;)</code></pre></p>
<h2 id="动态路由匹配"><a href="#动态路由匹配" class="headerlink" title="动态路由匹配"></a>动态路由匹配</h2><p>使用<code>:</code> 标记路径参数，当匹配到一个路由时，参数值会被设置到<code>this.$route.params</code>，以便在组件内使用。<br><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router(&#123;
  <span class="hljs-attr">routes</span>: [&#123;
    <span class="hljs-attr">path</span>: <span class="hljs-string">'/user/:id'</span>,
    <span class="hljs-attr">component</span>: User
  &#125;]
&#125;)</code></pre></p>
<p>可以设置多段路径参数</p>
<table>
<thead>
<tr>
<th style="text-align:left">路由设置</th>
<th style="text-align:left">匹配路径</th>
<th style="text-align:left">Params</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">/user/:id</td>
<td style="text-align:left">/user/233</td>
<td style="text-align:left">{id: ‘233’}</td>
</tr>
<tr>
<td style="text-align:left">/user/:id/name/:name</td>
<td style="text-align:left">/user/233/name/ilirus</td>
<td style="text-align:left">{id: ‘233’, name: ‘ilirus’}</td>
</tr>
</tbody>
</table>
<p><strong>当使用路径参数时, 例如<code>/user/233</code>到<code>/user/450</code>, 原来的组件实例会被复用, 这导致组件的生命周期钩子不会被调用</strong></p>
<p>所以应该对<code>$router</code>监测变化(watch)，或者使用导航守卫<br><pre><code class="hljs javascript">watch: &#123;
  <span class="hljs-string">'$route'</span> (to, <span class="hljs-keyword">from</span>) &#123;
    <span class="hljs-comment">// ...</span>
  &#125;
&#125;

beforeRouteUpdate(to, <span class="hljs-keyword">from</span>, next) &#123;
  <span class="hljs-comment">// ...</span>
&#125;</code></pre></p>
<h2 id="高级匹配模式"><a href="#高级匹配模式" class="headerlink" title="高级匹配模式"></a>高级匹配模式</h2><p><code>vue-router</code>使用<code>path-to-regexp</code>作为路径匹配引擎，所以支持更高级的匹配模式。<br><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router(&#123;
  <span class="hljs-attr">routes</span>: [
    <span class="hljs-comment">// 使用?来将参数定义为可选项</span>
    &#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/optional/:para?'</span>&#125;,
    &#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/optional/(:para/)?name'</span>&#125;
    <span class="hljs-comment">// 使用正则来实现仅匹配数字</span>
    &#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/number/:id(\\d+)'</span>&#125;
  ]
&#125;)</code></pre></p>
<h2 id="在JavaScript中进行路由跳转"><a href="#在JavaScript中进行路由跳转" class="headerlink" title="在JavaScript中进行路由跳转"></a>在JavaScript中进行路由跳转</h2><h3 id="router-push"><a href="#router-push" class="headerlink" title="router.push()"></a>router.push()</h3><p><code>router.push(location, onComplete?, onAbort?)</code><br>此方法会向history 栈添加一个新记录, 所以当用户点击后退按钮时，会返回到之前的URL</p>
<p>此方法接收一个字符串路径，或者一个描述地址的对象作为参数<br><pre><code class="hljs javascript"><span class="hljs-comment">// 字符串</span>
router.push(<span class="hljs-string">'/user'</span>)

<span class="hljs-comment">// 对象</span>
router.push(&#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/user'</span>&#125;)
router.push(&#123;<span class="hljs-attr">name</span>: <span class="hljs-string">'user'</span>&#125;)

<span class="hljs-comment">// 带参数</span>
<span class="hljs-comment">// -&gt; /user/233</span>
router.push(&#123;<span class="hljs-attr">name</span>: <span class="hljs-string">'user'</span>, <span class="hljs-attr">params</span>: &#123;<span class="hljs-attr">id</span>: <span class="hljs-string">'233'</span>&#125;&#125;)
<span class="hljs-comment">// -&gt; /user?id=233</span>
router.push(&#123;<span class="hljs-attr">name</span>: <span class="hljs-string">'user'</span>, <span class="hljs-attr">query</span>: &#123;<span class="hljs-attr">id</span>: <span class="hljs-string">'233'</span>&#125;&#125;)

<span class="hljs-comment">// 如果提供了path, 那么param会被忽略, query则不会</span>
<span class="hljs-comment">// -&gt; /user/233</span>
router.push(&#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/user/233'</span>&#125;)
<span class="hljs-comment">// -&gt; /user</span>
router.push(&#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'/user'</span>, <span class="hljs-attr">params</span>: &#123;<span class="hljs-attr">id</span>: <span class="hljs-string">'233'</span>&#125;&#125;)
<span class="hljs-comment">// -&gt; /user?id=233</span>
router.push(&#123;<span class="hljs-attr">path</span>: <span class="hljs-string">'user'</span>, <span class="hljs-attr">params</span>: &#123;<span class="hljs-attr">id</span>: <span class="hljs-string">'233'</span>&#125;&#125;)</code></pre></p>
<p><code>onComplete</code>和<code>onAbort</code> 回调函数会在导航成功完成(在所有的异步钩子被解析之后) 或者终止(导航到相同的路由、或在当前导航完成之前导航到另一个不同的路由) 的时候进行调用</p>
<h3 id="router-replace"><a href="#router-replace" class="headerlink" title="router.replace()"></a>router.replace()</h3><p><code>router.replace(location, onComplete?, onAbort?)</code><br>此方法会替换掉当前的history 记录, 所以当用户点击后退按钮时，不会返回到之前的URL</p>
<p>其余用法同<code>router.push()</code>方法</p>
<h3 id="router-go"><a href="#router-go" class="headerlink" title="router.go()"></a>router.go()</h3><p><code>router.go(n)</code><br>此方法接收一个整数作为参数，意为在history 记录中前进多少步<br><pre><code class="hljs javascript"><span class="hljs-comment">// 前进一步</span>
router.go(<span class="hljs-number">1</span>)
<span class="hljs-comment">// 后退一步</span>
router.go(<span class="hljs-number">-1</span>)
<span class="hljs-comment">// 前进十步, 如果记录不足, 则不会跳转</span>
router.go(<span class="hljs-number">10</span>)</code></pre></p>
<h2 id="视图命名"><a href="#视图命名" class="headerlink" title="视图命名"></a>视图命名</h2><p>可以在界面中拥有多个单独命名的视图，而不是只有一个单独的出口。</p>
<p>如果 router-view 没有设置名字，那么默认为 default。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">router-view</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-view</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">router-view</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"main"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-view</span>&gt;</span></code></pre>
<pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router (&#123;
  <span class="hljs-attr">routes</span>: [&#123;
    <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
    <span class="hljs-attr">components</span>: &#123;
      <span class="hljs-attr">default</span>: Nav,
      <span class="hljs-attr">main</span>: Main
    &#125;
  &#125;]
&#125;)</code></pre>
<h1 id="导航守卫"><a href="#导航守卫" class="headerlink" title="导航守卫"></a>导航守卫</h1><blockquote>
<p>参数或查询的改变并不会触发 进入/离开 的导航守卫。可以通过观察 $route 对象来应对这些变化，或使用 beforeRouteUpdate 的组件内守卫。</p>
</blockquote>
<h2 id="全局前置守卫"><a href="#全局前置守卫" class="headerlink" title="全局前置守卫"></a>全局前置守卫</h2><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router(&#123; ... &#125;)

<span class="hljs-comment">// 全局前置守卫</span>
<span class="hljs-comment">// to: 即将要进入的目标路由</span>
<span class="hljs-comment">// from: 正要离开的路由</span>
<span class="hljs-comment">// next: 放行, 不调用next方法则不会进入目标路由, 根据参数的不同, 效果也不同</span>
<span class="hljs-comment">// next(): 进行管道中的下一个钩子, 如果全部钩子执行完了, 则导航的状态就是confirmed</span>
<span class="hljs-comment">// next(false): 中断当前的导航, 如果浏览器的URL改变了, 会重置到from路由对应的地址</span>
<span class="hljs-comment">// next('/') | next(&#123;path: '/'&#125;): 跳转到另一个地址, 会使当前的导航被中断, 然后进行一个新的导航</span>
<span class="hljs-comment">// next(Error): 导航会被终止, 且会触发router.onError()</span>
router.beforeEach(<span class="hljs-function">(<span class="hljs-params">to, <span class="hljs-keyword">from</span>, next</span>) =&gt;</span> &#123;
  <span class="hljs-comment">// ...</span>
&#125;)</code></pre>
<p>当一个导航触发时，全局前置守卫按照创建顺序调用。守卫是异步解析执行，此时导航在所有守卫<code>resolve</code>完之前会一直处于等待中。</p>
<h2 id="全局后置钩子"><a href="#全局后置钩子" class="headerlink" title="全局后置钩子"></a>全局后置钩子</h2><p>此方法不接收<code>next()</code>函数也不会改变导航本身<br><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router(&#123; ... &#125;)

router.afterEach(<span class="hljs-function">(<span class="hljs-params">to, <span class="hljs-keyword">from</span></span>) =&gt;</span> &#123;
  <span class="hljs-comment">// ...</span>
&#125;)</code></pre></p>
<h2 id="路由独享守卫"><a href="#路由独享守卫" class="headerlink" title="路由独享守卫"></a>路由独享守卫</h2><p>用法与全局前置守卫相同<br><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-keyword">new</span> Router(&#123;
  <span class="hljs-attr">routes</span>: [&#123;
    <span class="hljs-attr">path</span>: <span class="hljs-string">'/home'</span>,
    <span class="hljs-attr">component</span>: Home,
    <span class="hljs-attr">beforeEnter</span>: <span class="hljs-function">(<span class="hljs-params">to, <span class="hljs-keyword">from</span>, next</span>) =&gt;</span> &#123;
      <span class="hljs-comment">// ...</span>
    &#125;
  &#125;]
&#125;)</code></pre></p>
<h2 id="组件内的守卫"><a href="#组件内的守卫" class="headerlink" title="组件内的守卫"></a>组件内的守卫</h2><p>可以在路由组件内直接定义这些路由导航守卫<br><pre><code class="hljs javascript"><span class="hljs-comment">// 在渲染该组件的对应路由被 confirm 前调用</span>
<span class="hljs-comment">// 不能 获取组件实例 this, 因为当守卫执行前，组件实例还没被创建</span>
beforeRouteEnter(to, <span class="hljs-keyword">from</span>, next) &#123;
  <span class="hljs-comment">// ...</span>
&#125;,

<span class="hljs-comment">// 在当前路由改变，但是该组件被复用时调用</span>
<span class="hljs-comment">// 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，</span>
<span class="hljs-comment">// 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。</span>
<span class="hljs-comment">// 可以访问组件实例 this</span>
beforeRouteUpdate(to, <span class="hljs-keyword">from</span>, next) &#123;
  <span class="hljs-comment">// ...</span>
&#125;,

<span class="hljs-comment">// 导航离开该组件的对应路由时调用</span>
<span class="hljs-comment">// 可以访问组件实例 this</span>
<span class="hljs-comment">// 通常用来阻止用户在还未保存修改前突然离开</span>
<span class="hljs-comment">// 该导航可以通过 next(false) 来取消</span>
beforeRouteLeave(to, <span class="hljs-keyword">from</span>, next) &#123;
  <span class="hljs-comment">// ...</span>
&#125;</code></pre></p>
<p><code>beforeRouteEnter</code> 不能访问到this, 但可以通过给<code>next()</code>传递回调来访问组件实例, 且只有<code>beforeRouteEnter</code>方法支持给<code>next()</code>函数传递回调<br><pre><code class="hljs javascript">beforeRouteEnter(to, <span class="hljs-keyword">from</span>, next) &#123;
  next(<span class="hljs-function"><span class="hljs-params">vm</span> =&gt;</span> &#123;
    <span class="hljs-comment">// ...</span>
  &#125;)
&#125;,</code></pre></p>
<h1 id="过渡动效"><a href="#过渡动效" class="headerlink" title="过渡动效"></a>过渡动效</h1><p>使用<code>transition</code>组件给<code>router-view</code>添加一些过渡效果<br><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">transition</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"slide"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-view</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-view</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">transition</span>&gt;</span></code></pre></p>
<p>也可以动态设置过渡效果<br><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">transition</span> <span class="hljs-attr">:name</span>=<span class="hljs-string">"transitionType"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">router-view</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">router-view</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">transition</span>&gt;</span></code></pre></p>
<pre><code class="hljs javascript">watch: &#123;
  <span class="hljs-string">'$route'</span> (to, <span class="hljs-keyword">from</span>) &#123;
    <span class="hljs-keyword">const</span> toDepth = to.path.split(<span class="hljs-string">'/'</span>).length
    <span class="hljs-keyword">const</span> fromDepth = <span class="hljs-keyword">from</span>.path.split(<span class="hljs-string">'/'</span>).length
    <span class="hljs-keyword">this</span>.transitionType = toDepth &lt; fromDepth ? <span class="hljs-string">'slide-right'</span> : <span class="hljs-string">'slide-left'</span>
  &#125;
&#125;</code></pre>
            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/Vue-js/">Vue.js</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/JavaScript/">JavaScript</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/Vue-js/">Vue.js</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" rel="nofollow noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/blog/2019/06/01/ES6中的尾递归/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">ES6中的尾递归</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/blog/2018/12/10/使用Vue-cli搭建Vue项目/">
                        <span class="hidden-mobile">使用Vue-cli搭建Vue项目</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="lv-container" data-id="city" data-uid="MTAyMC80NTMxNi8yMTgyOQ==">
    <script type="text/javascript">
      function loadLivere() {
        addScript('https://cdn-city.livere.com/js/embed.dist.js');
      }
      createObserver(loadLivere, 'lv-container');
    </script>
    <noscript>为正常使用来必力评论功能请允许 JavaScript 运行</noscript>
  </div>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Vue Router的安装与使用&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script type="text/javascript">
      //定义获取词语下标
      var a_idx = 0;
      jQuery(document).ready(function ($) {
        //点击body时触发事件
        $("body").click(function (e) {
          //需要显示的词语
          var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
          //设置词语给span标签
          var $i = $("<span/>").text(a[a_idx]);
          //下标等于原来下标+1  余 词语总数
          a_idx = (a_idx + 1) % a.length;
          //获取鼠标指针的位置，分别相对于文档的左和右边缘。
          //获取x和y的指针坐标
          var x = e.pageX, y = e.pageY;
          //在鼠标的指针的位置给$i定义的span标签添加css样式
          $i.css({
            "z-index": 999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": rand_color()
          });
          // 随机颜色
          function rand_color() {
            return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
          }
          //在body添加这个标签
          $("body").append($i);
          //animate() 方法执行 CSS 属性集的自定义动画。
          //该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的，这样就可以创建动画效果。
          //详情请看http://www.w3school.com.cn/jquery/effect_animate.asp
          $i.animate({
            //将原来的位置向上移动180
            "top": y - 180,
            "opacity": 0
            //1500动画的速度
          }, 1500, function () {
            //时间到了自动删除
            $i.remove();
          });
        });
      })
      ;
    </script>
  














<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/tororo.model.json"},"display":{"position":"left","width":300,"height":300},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
